﻿using Autofac;
using Autofac.Extras.DynamicProxy;
using MyCompany.MyProject.Common;
using MyCompany.MyProject.Extensions.AOP;
using MyCompany.MyProject.IService;
using MyCompany.MyProject.Repository.Base;
using MyCompany.MyProject.Repository.UnitOfWork;
using MyCompany.MyProject.Service;
using System.Reflection;

namespace MyCompany.MyProject.Extensions.ServiceExtensions
{
    public class AutofacModuleRegister : Autofac.Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            var basePath = AppContext.BaseDirectory;
            var serviceDllFile = Path.Combine(basePath, "MyCompany.MyProject.Service.dll");
            var repositoryDllFile = Path.Combine(basePath, "MyCompany.MyProject.Repository.dll");

            // AOP 切面
            var aopTypes = new List<Type> { /*typeof(ServiceAOP), typeof(TranAOP) */};
            //builder.RegisterType<ServiceAOP>();
            //builder.RegisterType<TranAOP>();

            if (AppSettings.app("AppSettings", "LogAop", "Enabled").ObjToBool())
            {
                builder.RegisterType<LogAop>();
                aopTypes.Add(typeof(LogAop));
            }

            // 注册泛型仓储
            builder.RegisterGeneric(typeof(BaseRepository<>)).As(typeof(IBaseRepository<>)).InstancePerDependency();
            builder.RegisterGeneric(typeof(BaseService<>)).As(typeof(IBaseService<>))
                .EnableInterfaceInterceptors()
                .InterceptedBy(aopTypes.ToArray())
                .InstancePerDependency();

            // 获取 Service.dll 程序集服务，并注册
            var assemblyServices = Assembly.LoadFrom(serviceDllFile);
            builder.RegisterAssemblyTypes(assemblyServices)
                .AsImplementedInterfaces()
                .InstancePerDependency()
                .EnableInterfaceInterceptors()
                .InterceptedBy(aopTypes.ToArray())
                .PropertiesAutowired();

            // 获取 Repository.dll 程序集并注册
            var assemblysRepository = Assembly.LoadFrom(repositoryDllFile);
            builder.RegisterAssemblyTypes(assemblysRepository)
                .AsImplementedInterfaces()
                .InstancePerDependency()
                .PropertiesAutowired();

            // 需要注册工作单元
            builder.RegisterType<UnitOfWorkManage>().As<IUnitOfWorkManage>()
                .AsImplementedInterfaces()
                .InstancePerDependency()
                .PropertiesAutowired();
        }
    }
}
